// pages/game/shoot/shoot.js
//配置信息
const conf = {
  rollTop: 170, //旋转圆圈距离顶部的距离
  rollWidth: 121, //旋转圆圈的半径
  rollDuration: 3000, //顶部旋转一周时长
  shootSpeed: 8, //子弹发射速度
  bulletMoveDuration: 10, //子弹移动间隔时间
  paoX: 104, //发射按钮中心点到右边的距离
  paoY: 196, //发射按钮中心点到下边的距离
  paoToBulletDistance: 184, //发射按钮中心点到子弹原图中心点
  bulletw: 82, //子弹图片原图的宽度
  bulleth: 82, //子弹图片原图的高度
  targetAngle: 60, //圆的开口大小，初始从角度0开始计算
}

const app = getApp()
const md5 = require('../../../utils/md5.js');
Page({
  data: {
    animatRoll: {},
    rollWidth: null,
    paoRotate: '0',
    bulletRight: '20',
    bulletBottom: '20',
    showBullet: false,
    isFirstShooted: false,
  },
  onLoad: function(options) {
    this.goods_id = options.goods_id;
    this.group_id = options.group_id;
    this.canShoot = false;
    //创建动画实例
    this.animatRoll = wx.createAnimation({
      timingFunction: 'linear',
    });
    this.animatShoot = wx.createAnimation({
      timingFunction: 'linear',
    });
    //获取商品信息
    this.getGoodsInfo();
    //获取碰撞性息
    this.getImpactPoint();

    this.setData({
      pageHeight: app.globalData.pageHeight
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    if (this.moveInterval) {
      clearInterval(this.moveInterval);
    }
    if (this.waitResultInterval) {
      clearInterval(this.waitResultInterval);
    }
    if (this.dropInterval) {
      clearInterval(this.dropInterval);
    }
    if (this.rotateTimeout) {
      clearTimeout(this.rotateTimeout);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.pageShow = true;
    //获取用户信息
    this.getMyInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.pageShow = false;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //顶部旋转开启
    this.rotateNum = 0;
    this.rotate();
  },

  /**
   * 用户信息
   */
  getMyInfo: function() {
    app.getUserInfo((res) => {
      this.setData({
        myinfo: res
      })
    })
  },

  /**
   * 获取商品信息
   */
  getGoodsInfo: function() {
    app.Ajax({
      url: '/api/index.php?app=goods&act=detail',
      data: {
        goods_id: this.goods_id,
        group_id: this.group_id,
      },
      success: (res) => {
        this.setData({
          goods_info: res
        })
        //默认用商品的第一个sku，如果没有库存，则再找第二个
        var goodsIdx = 0;
        while (!this.sku_id && goodsIdx < res.skus.length) {
          if (res.skus[goodsIdx].stock > 0) {
            this.sku_id = res.skus[goodsIdx].sku_id;
          }
          goodsIdx++;
        }
        //没有库存
        if (this.sku_id == null) {
          this.messageToast({
            id: 1,
            title: '抱歉',
            content: '商品库存不足，请选择其他商品',
            showCancel: false,
            confirmText: '去看看',
          }, 2);
        }
      },
      fail: (err) => {
        this.messageToast({
          id: 2,
          title: '抱歉',
          content: err,
          showCancel: false,
          confirmText: '返回上一页',
        }, 2);
      }
    })
  },

  /**
   *  获取碰撞点
   *  炮口永远都是指向商品中心，因此炮口角度会随着屏幕高度的变化而改变
   */
  getImpactPoint: function() {
    //发射按钮中心点
    this.shootPoint = {
      x: 750 - conf.paoX,
      y: app.globalData.pageHeight - conf.paoY,
    }

    //最终命中点
    this.goodsPoint = {
      x: 375,
      y: conf.rollTop + conf.rollWidth
    }
    // console.log(this.goodsPoint)

    //炮的角度
    var paoTan = (this.shootPoint.x - this.goodsPoint.x) / (this.shootPoint.y - this.goodsPoint.y);
    this.paoRotate = Math.atan(paoTan) * 180 / Math.PI;
    console.log('炮口角度', this.paoRotate)

    //碰撞点
    var rotateAngle = this.paoRotate * Math.PI / 180;
    this.impactPoint = {
      x: this.goodsPoint.x + conf.rollWidth * Math.sin(rotateAngle),
      y: this.goodsPoint.y + conf.rollWidth * Math.cos(rotateAngle)
    }
    this.setData({
      impactPoint: this.impactPoint
    })
    // console.log(this.impactPoint)

    this.setData({
      paoRotate: this.paoRotate,
      rollWidth: conf.rollWidth,
    })

    //已知圆圈开口角度和子弹宽度
    //计算可以射入圆圈的最大旋转角度和几率百分比
    var minImpactRotate = Math.asin((conf.bulletw / 2) / conf.rollWidth);
    var minImpactAngle = minImpactRotate * 180 / Math.PI;

    //因为圆圈一直在顺时针旋转，所以触碰旋转角度需要适当扩大10度让用户从视觉上感受到正常
    this.minRollAngle = 270 - (this.paoRotate + conf.targetAngle / 2) + minImpactAngle - 10;
    this.maxRollAngle = 270 - (this.paoRotate + conf.targetAngle / 2) + 60 - minImpactAngle;

    console.log('最小碰撞角度', minImpactAngle);

    //计算子弹的初始位置
    this.initBulletPosition();
  },

  /**
   * 计算子弹的初始位置
   */
  initBulletPosition: function() {
    var rotateAngle = this.paoRotate * Math.PI / 180;
    //子弹中心点到发射按钮中心的X、Y轴偏移量
    var moveX = conf.paoToBulletDistance * Math.sin(rotateAngle);
    var moveY = conf.paoToBulletDistance * Math.cos(rotateAngle);

    //子弹中心点初始位置
    this.bulletCenterX = conf.paoX + moveX;
    this.bulletCenterY = conf.paoY + moveY;

    //子弹的碰撞点初始位置
    this.bulletImpact = {
      x: 750 - (this.bulletCenterX + (conf.bulleth / 2 - 28) * Math.sin(rotateAngle)),
      y: app.globalData.pageHeight - (this.bulletCenterY + (conf.bulleth / 2 - 28) * Math.cos(rotateAngle))
    }
    // this.setData({
    //   bulletImpactTop: this.bulletImpact.y,
    //   bulletImpactLeft: this.bulletImpact.x
    // })

    //子弹距离屏幕底部、最右边的初始距离
    this.bulletBottom = conf.paoY + moveY - conf.bulleth / 2;
    this.bulletRight = conf.paoX + moveX - conf.bulletw / 2;
    this.animatShoot.translate(0, 0).rotate(0).step({
      duration: 0
    })
    this.setData({
      showBullet: false,
      animatShoot: this.animatShoot.export(),
      bulletBottom: this.bulletBottom,
      bulletRight: this.bulletRight,
    })
    //允许射击
    setTimeout(() => {
      this.canShoot = true;
    }, 200);
  },

  /**
   * 准备射击
   */
  shootPrepare: function() {
    //是否可以射击
    if (!this.canShoot) {
      return;
    }
    if (!this.canIShootOrNot()) {
      return;
    }

    this.setData({
      shootClick: true
    })
  },

  /**
   * 射击
   */
  shootEvent: function() {
    //是否可以射击
    if (!this.canShoot) {
      return;
    }
    if (!this.canIShootOrNot()) {
      return;
    }

    this.canShoot = false;
    this.setData({
      shootClick: false
    })
    this.shootAnimationHasDone = false; //射击动画已经结束
    //判断是否能够射中并射击
    this.isShootingCenter();
    this.shoot();

    //通知后台游戏结果
    var ts = parseInt(new Date().getTime() / 1000);
    var data = {
      score: this.shootCenter ? 1 : 0,
      ts: ts
    };
    if (this.set_id) {
      data.set_id = this.set_id;
      var sign = 'score' + (this.shootCenter ? 1 : 0) + 'set_id' + this.set_id + 'ts' + ts;
      sign = md5.hex_md5(sign);
      sign = app.globalData.userInfo.platform_secret_key + sign;
      sign = md5.hex_md5(sign);
      data.sign = sign;
    } else {
      data.goods_id = this.goods_id;
      data.sku_id = this.sku_id;
      var sign = 'goods_id' + this.goods_id + 'score' + (this.shootCenter ? 1 : 0) + 'sku_id' + this.sku_id + 'ts' + ts;
      sign = md5.hex_md5(sign);
      sign = app.globalData.userInfo.platform_secret_key + sign;
      sign = md5.hex_md5(sign);
      data.sign = sign;
    }
    app.Ajax({
      url: '/api/game_wawa/create',
      data: data,
      success: (res) => {
        // console.log(res)
        //更新用户信息
        this.getMyInfo();
        //回调结果参数
        this.set_id = res.set_id; //场次id
        this.is_strong = res.is_strong; //是否抓中
        this.playResult = res;
        //如果返回回调时，射击动画已经结束，则显示射击结果
        if (this.shootAnimationHasDone && this.playResult.score == 1) {
          this.shootSuccess();
        }
      },
      fail: (err) => {
        this.messageToast(err);
        this.initBulletPosition();
      }
    })
  },

  /**
   * 是否可以射击
   */
  canIShootOrNot: function() {
    if (app.globalData.isConnected === false) {
      this.messageToast('无网络，请检查您的网络连接情况');
      return false;
    }
    if (this.data.myinfo.stars < this.data.goods_info.play_price) {
      this.messageToast({
        id: 4,
        title: '温馨提示',
        content: '您的星星余额不足\n请完成任务获得星星',
        cancelText: '暂时放弃',
        confirmText: '马上去赚星',
        confirmBgColor: '#ffda44'
      }, 2);
      return false;
    }

    return true;
  },

  /**
   * 计算是否可以射中
   */
  isShootingCenter: function() {
    var self = this;
    //子弹碰撞点到圆圈碰撞点的飞行距离
    var bulletMoveDistance = Math.sqrt(Math.pow(this.bulletImpact.y - this.impactPoint.y, 2) + Math.pow(this.bulletImpact.x - this.impactPoint.x, 2));
    //子弹移动速度
    this.shootSpeed = conf.shootSpeed;
    // console.log(bulletMoveDistance)

    if (this.is_strong == 0) { //如果是低中奖率
      this.is_strong = null;
      //如果正常可以射中，则需要控制子弹速度
      var result = isShootedOrNot();
      if (result === true) {
        var minFlyTime = self.minRollAngle / 360 * self.rollDuration + self.startTime - new Date().getTime();
        var maxFlyTime = self.maxRollAngle / 360 * self.rollDuration + self.startTime - new Date().getTime();
        var minShootSpeed = bulletMoveDistance * conf.bulletMoveDuration / minFlyTime;
        var maxShootSpeed = bulletMoveDistance * conf.bulletMoveDuration / maxFlyTime;
        if (Math.abs(self.shootSpeed - minShootSpeed) >= Math.abs(self.shootSpeed - maxShootSpeed)) {
          self.shootSpeed = maxShootSpeed - 0.1;
        } else {
          self.shootSpeed = minShootSpeed + 0.2;
        }
        console.log(maxShootSpeed + '>>' + self.shootSpeed + '>>' + minShootSpeed)
        //重新计算结果
        this.shootCenter = isShootedOrNot();
      } else {
        this.shootCenter = result;
      }
      return;
    }

    //计算结果
    this.shootCenter = isShootedOrNot();

    //是否射中函数
    function isShootedOrNot() {
      var bulletFlyTime = bulletMoveDistance / self.shootSpeed * conf.bulletMoveDuration;
      var arrivedTime = new Date().getTime() + bulletFlyTime;
      // console.log('arrivedTime', arrivedTime)
      var timeDiff = arrivedTime - self.startTime;

      var shootCenter = false;
      // console.log('子弹移速', self.shootSpeed);
      console.log(self.minRollAngle / 360 * self.rollDuration + '<<' + timeDiff + '<<' + self.maxRollAngle / 360 * self.rollDuration);
      if (timeDiff >= self.minRollAngle / 360 * self.rollDuration &&
        timeDiff <= self.maxRollAngle / 360 * self.rollDuration) {
        shootCenter = true;
      }
      return shootCenter;
    }
  },

  /**
   * 计算设计移动轨道
   */
  shoot: function() {
    var destinationPoint;
    if (this.shootCenter === true) {
      destinationPoint = this.goodsPoint;
    } else {
      destinationPoint = this.impactPoint;
    }
    //子弹碰撞点到圆圈碰撞点的飞行距离
    var bulletMoveDistance = Math.sqrt(Math.pow(this.bulletImpact.y - destinationPoint.y, 2) + Math.pow(this.bulletImpact.x - destinationPoint.x, 2));
    var bulletFlyTime = bulletMoveDistance / this.shootSpeed * conf.bulletMoveDuration;
    //创建动画实例
    this.animatShoot.translate((destinationPoint.x - this.bulletImpact.x) / app.globalData.pixelRatio, (destinationPoint.y - this.bulletImpact.y) / app.globalData.pixelRatio).rotate(360 * bulletFlyTime / 1000).step({
      duration: bulletFlyTime,
    })
    //先显示子弹，10毫秒后开始运动
    this.setData({
      showBullet: true
    })
    setTimeout(() => {
      this.setData({
        animatShoot: this.animatShoot.export()
      });
    }, 10);
    //子弹飞行到目标点后，显示是否射中
    setTimeout(() => {
      if (this.shootCenter === true) {
        this.shootSuccess();
      } else {
        this.shootFailed();
      }
    }, bulletFlyTime);
  },

  /**
   * 射中了
   */
  shootSuccess: function() {
    if (this.waitResultInterval) {
      clearInterval(this.waitResultInterval);
    }

    //如果后台收到了结果回调才显示
    if (this.playResult) {
      if (this.playResult.order_id == 0) {
        this.setData({
          isFirstShooted: true,
        })
        this.messageToast('再射中一次就能拿走奖品啦~');
      } else {
        this.messageToast({
          id: 3,
          image: {
            url: 'style/img/shoot/success.png',
            width: 390,
            height: 280
          },
          content: '成功获得了奖品\n请在15天内领取否则视为放弃奖励',
          contentColor: '#f23150',
          showCancel: false,
          confirmText: '马上领取',
        }, 2);
      }
      this.playResult = null;
      this.initBulletPosition();
    } else {
      this.loadingIdx = 1;
      this.waitResultInterval = setInterval(() => {
        if (this.loadingIdx == 1) {
          this.loadingIdx = 2;
          this.messageToast('网络繁忙，请稍等片刻.');
        } else if (this.loadingIdx == 2) {
          this.loadingIdx = 3;
          this.messageToast('网络繁忙，请稍等片刻..');
        } else if (this.loadingIdx == 3) {
          this.loadingIdx = 1;
          this.messageToast('网络繁忙，请稍等片刻...');
        }
      }, 500);
    }
    this.shootAnimationHasDone = true;
  },

  /**
   * 未射中
   */
  shootFailed: function() {
    //显示碰撞火花
    this.setData({
      impacted: true
    })
    setTimeout(() => {
      this.setData({
        impacted: false
      })
    }, 100);
    this.playResult = null;

    //失败的星星动画
    this.animatShoot.translate(-400, 100).rotate(360 * 2).step({
      duration: 800,
    })
    this.setData({
      animatShoot: this.animatShoot.export()
    });
    setTimeout(() => {
      this.initBulletPosition();
      this.shootAnimationHasDone = true;
    }, 800);
  },

  /**
   * 计算旋转数值
   */
  rotate: function() {
    //第一个气球匀速，第二个气球变速
    if (this.data.isFirstShooted === false) {
      this.rollDuration = conf.rollDuration; //匀速
    } else {
      this.rollDuration = Math.random() * 1000 + conf.rollDuration - 1000; //变速
    }
    //记录该次旋转的开始时间
    this.startTime = new Date().getTime();
    if (this.pageShow) {
      this.rotateNum++;
      this.rotateMove();
    }
    this.rotateTimeout = setTimeout(() => {
      this.rotate();
    }, this.rollDuration);
  },

  /**
   * 开始旋转
   */
  rotateMove: function() {
    this.animatRoll.rotate(360 * this.rotateNum).step({
      duration: this.rollDuration,
    })
    this.setData({
      animatRoll: this.animatRoll.export()
    });
  },


  /**
   * 立即购买
   */
  goodsBuy: function() {
    this.setData({
      isBuying: true,
      canScroll: false,
    })
  },

  /**
   * 取消购买
   */
  buyCancel: function() {
    this.setData({
      isBuying: false,
      canScroll: true,
    })
  },

  /**
   * 返回首页
   */
  backToHome: function() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 商品详情
   */
  viewGoodsDetail: function() {
    wx.navigateTo({
      url: '../../goods_detail/goods_detail?group_id=' + this.group_id + '&goods_id=' + this.goods_id,
    })
  },

  /**
   * 消息提示
   */
  messageToast: function(param, toastType) {
    toastType = toastType || 0;
    if (toastType == 0) {
      this.setData({
        toastType: 0,
        message: param
      })
    } else if (toastType == 2) {
      this.setData({
        toastType: 2,
        modalOptions: param
      })
    }
  },

  /**
   * 消息确认
   */
  confirmEvent: function(e) {
    var toastid = e.detail.toastid;
    if (toastid == 1) { //库存不足，看看其他商品
      wx.navigateBack({
        delta: 1
      })
    } else if (toastid == 2) { //商品信息获取失败
      wx.navigateBack({
        delta: 1
      })
    } else if (toastid == 3) { //领取商品
      wx.redirectTo({
        url: '../../goods/catched_list/catched_list',
      })
    } else if (toastid == 4) { //星星不足
      wx.switchTab({
        url: '../../task/mainpage/mainpage',
      })
    }
  }
})